package main

import (
	"log"
	"net/http"
	"net/http/cookiejar"
)

func (w *WebSocketApp) GetTTWID() string {
	if w.ttwid != "" {
		return w.ttwid
	}

	// 初始化 HTTP Client，并设置 CookieJar 来存储 cookies
	if w.httpClient == nil {
		jar, _ := cookiejar.New(nil)
		w.httpClient = &http.Client{
			Jar: jar,
		}
	}

	// 设置请求头
	req, err := http.NewRequest("GET", w.LiveURL, nil)
	if err != nil {
		log.Fatalf("请求直播间 URL 错误: %v", err)
	}
	req.Header.Set("User-Agent", w.UserAgent)

	// 发送请求
	resp, err := w.httpClient.Do(req)
	if err != nil {
		log.Fatalf("请求直播间 URL 失败: %v", err)
	}
	defer resp.Body.Close()

	// 从响应中获取 ttwid cookie
	for _, cookie := range resp.Cookies() {
		if cookie.Name == "ttwid" {
			w.ttwid = cookie.Value
			break
		}
	}

	if w.ttwid == "" {
		log.Println("未能获取到 ttwid")
	}

	return w.ttwid
}
